#include "discovery_private_device.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include "check_common.h"
#include "cjson_common.h"

void *discovery_private_device(void *arg)
{
    int sockfd;
    struct sockaddr_in server_addr, client_addr;
    struct ip_mreq mreq;
    char buffer[BUFFER_SIZE];
    socklen_t addr_len;
    char* eth_name = "eth0";
    char ip_addr[16] = {0};
    // 创建UDP socket
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        perror("socket creation failed");
        return NULL;
    }

    // 设置服务器地址结构
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(DISCOVERY_PORT);

    // 绑定socket
    if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("bind failed");
        close(sockfd);
        return NULL;
    }

    // 设置多播选项
    memset(&mreq, 0, sizeof(mreq));
    mreq.imr_multiaddr.s_addr = inet_addr(MULTICAST_IP);
    mreq.imr_interface.s_addr = htonl(INADDR_ANY);

    if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&mreq, sizeof(mreq)) < 0) {
        perror("setsockopt failed");
        close(sockfd);
        return NULL;
    }

    if(0 > get_local_ipaddr(eth_name, ip_addr))
    {
        perror("get_local_ipaddr failed");
        close(sockfd);
        return NULL;
    }

    printf("Waiting for clients on multicast address %s:%d\n", MULTICAST_IP, DISCOVERY_PORT);
    printf("hostinfo->ip=%s\n",ip_addr);
    fflush(stdout);

    // 无限循环等待接收数据
    while (1) {
        addr_len = sizeof(client_addr);
        // 接收客户端的探测请求
        int n = recvfrom(sockfd, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&client_addr, &addr_len);
        if (n < 0) {
            perror("recvfrom failed");
            continue;
        }

        // 响应探测请求
        cJSON* json =  cJSON_CreateObject();
        CHECK_POINTER_GO(json, end);

        CJSON_SET_STRING(json, "device_addr", ip_addr, end);
        CJSON_SET_NUMBER(json, "http_port", 8080, end);

        char* buff = cJSON_PrintUnformatted(json);
        CHECK_POINTER_GO(buff, end);
        LOG_INFO("buff->%s\n", buff);

        char *client_cmp_msg = "discovery cdjp device";
        if(strncmp(buffer, client_cmp_msg, strlen(client_cmp_msg)) != 0)
        {
            LOG_ERR("client send message not match!\n");
            continue;
        }

        if (sendto(sockfd, buff, strlen(buff), 0, (struct sockaddr *)&client_addr, addr_len) < 0) {
            perror("sendto failed");
        }

        free(buff);
        printf("Response sent to client at IP: %s\n", inet_ntoa(client_addr.sin_addr));
        
    end:
        cJSON_free(json);
    }

    close(sockfd);
    return NULL;
}

void *discovery_private_device2(void *arg)
{
    int sockfd;
    struct sockaddr_in server_addr, client_addr;
    struct ip_mreq mreq;
    char buffer[BUFFER_SIZE];
    socklen_t addr_len;
    char* eth_name = "eth0";
    char ip_addr[16] = {0};
    // 创建UDP socket
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        perror("socket creation failed");
        return NULL;
    }

    // 设置服务器地址结构
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(3702);

    // 绑定socket
    if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("bind failed");
        close(sockfd);
        return NULL;
    }

    // 设置多播选项
    memset(&mreq, 0, sizeof(mreq));
    mreq.imr_multiaddr.s_addr = inet_addr("239.255.255.250");
    mreq.imr_interface.s_addr = htonl(INADDR_ANY);

    if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&mreq, sizeof(mreq)) < 0) {
        perror("setsockopt failed");
        close(sockfd);
        return NULL;
    }

    if(0 > get_local_ipaddr(eth_name, ip_addr))
    {
        perror("get_local_ipaddr failed");
        close(sockfd);
        return NULL;
    }

    printf("Waiting for clients on multicast address %s:%d\n", "239.255.255.250", 3702);
    printf("hostinfo->ip=%s\n",ip_addr);
    fflush(stdout);

    // 无限循环等待接收数据
    while (1) {
        addr_len = sizeof(client_addr);
        // 接收客户端的探测请求
        int n = recvfrom(sockfd, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&client_addr, &addr_len);
        if (n < 0) {
            perror("recvfrom failed");
            continue;
        }

        // 响应探测请求
        cJSON* json =  cJSON_CreateObject();
        CHECK_POINTER_GO(json, end);

        CJSON_SET_STRING(json, "device_addr", ip_addr, end);
        CJSON_SET_NUMBER(json, "http_port", 8080, end);

        char* buff = cJSON_PrintUnformatted(json);
        CHECK_POINTER_GO(buff, end);
        LOG_INFO("buff->%s\n", buff);

        char *client_cmp_msg = "discovery cdjp device";
        if(strncmp(buffer, client_cmp_msg, strlen(client_cmp_msg)) != 0)
        {
            LOG_ERR("client send message not match!\n");
            continue;
        }

        if (sendto(sockfd, buff, strlen(buff), 0, (struct sockaddr *)&client_addr, addr_len) < 0) {
            perror("sendto failed");
        }

        free(buff);
        printf("Response sent to client at IP: %s\n", inet_ntoa(client_addr.sin_addr));
        
    end:
        cJSON_free(json);
    }

    close(sockfd);
    return NULL;
}


int get_local_ipaddr(const char* ethname, char *ip)
{
    int socket_fd;
    struct sockaddr_in *sin;
    struct ifreq ifr;

    socket_fd = socket(AF_INET,SOCK_DGRAM,0); 
    if(socket_fd ==-1)
    {
        perror("socket error!\n");
        return -1;
    }

    memset(&ifr, 0, sizeof(ifr));
    strcpy(ifr.ifr_name, ethname);

    if(ioctl(socket_fd, SIOCGIFADDR, &ifr) < 0)
    {
        printf("ethname=%s: ", ethname);
        perror("ioctl error\n");
        close(socket_fd);
        return -1;
    }
    sin = (struct sockaddr_in *)&(ifr.ifr_addr);
    strcpy(ip, inet_ntoa(sin->sin_addr));
    close(socket_fd);
    return 0;
}
